var wordsSubmited = new Array();
var drawing = false;
var selecting = false;
var context;
var offset_left = 0;
var offset_top = 0;
var boxesX;
var boxesY;
var sizeX = 500;
var sizeY = 500;
var boxes = new Array();
var lastSelected = {}
var path = new Array();
var player;
var letters;
var minutes;
var seconds;
var gameId;
var points = 0;
var cornerSensitivity = 0.2;
var needToRepaint = true;
var gameProxy = new GameProxy("http://" + window.location.hostname + ":8080/weba-novare/rs/ruzzle");
var charOffsetX = 30;
var charOffsetY = 70;


function start_canvas (letters, player, size, minutes, seconds, gameId) {
    this.player = player;
    this.letters = letters;
    this.boxesX = size;
    this.boxesY = size;
    
    if (size === 3) {
        this.charOffsetX = 45;
        this.charOffsetY = 100;
    }
    else if (size == 4) {
        this.charOffsetX = 40;
        this.charOffsetY = 90;
    }
    else if (size == 6) {
        this.charOffsetX = 10;
        this.charOffsetY = 68;
    }
    
    
    this.minutes = minutes;
    this.seconds = seconds;
    this.gameId = gameId;
    var totalSeconds = this.minutes*60 + this.seconds;
    this.CreateTimer("timer", totalSeconds);
    this.output();
    var ruzzle = document.getElementById ("apa");
    context = ruzzle.getContext ("2d");
    ruzzle.onmousedown = function (event) {
        mousedown(event)
    };
    ruzzle.onmousemove = function (event) {
        mousemove(event)
    };
    ruzzle.onmouseup   = function (event) {
        mouseup(event)
    };
    for (var o = ruzzle; o ; o = o.offsetParent) {
        offset_left += (o.offsetLeft - o.scrollLeft);
        offset_top  += (o.offsetTop - o.scrollTop);
    }
    createBoxes();
    drawBoxes();
    this.lastSelected.x = -1;
    this.lastSelected.y = -1;
}

function getPosition(evt) {
    evt = (evt) ?  evt : ((event) ? event : null);
    var left = 0;
    var top = 0;
    var ruzzle = document.getElementById("apa");

    if (evt.pageX) {
        left = evt.pageX;
        top  = evt.pageY;
    } 
    else if (document.documentElement.scrollLeft) {
        left = evt.clientX + document.documentElement.scrollLeft;
        top  = evt.clientY + document.documentElement.scrollTop;
    } 
    else  {
        left = evt.clientX + document.body.scrollLeft;
        top  = evt.clientY + document.body.scrollTop;
    }
    left -= offset_left;
    top -= offset_top;

    return {
        x : left, 
        y : top
    }; 
}
function mousedown(event) {
    selecting = true;
    mousemove(event);
    drawBoxes();
}
function mousemove(event) {
    if (!selecting)
        return;
    var location = getPosition(event);
    
    var diffX = location.x/(this.sizeX/this.boxesX) - Math.floor(location.x/(this.sizeX/this.boxesX));
    var diffY = location.y/(this.sizeY/this.boxesY) - Math.floor(location.y/(this.sizeY/this.boxesY));

    
    if ((diffX > this.cornerSensitivity && diffX < (1 - this.cornerSensitivity)) && (diffY > this.cornerSensitivity && diffY < (1-this.cornerSensitivity)) ) {
        var x = Math.floor(location.x/(this.sizeX/this.boxesX));
        var y = Math.floor(location.y/(this.sizeY/this.boxesY));
        
        if (x + this.boxesX*y < this.boxes.length) {
            if (this.boxes[x + this.boxesX*y].selected === false) {
                this.needToRepaint = true;
                if (this.lastSelected.x === -1) {
                    this.boxes[x + this.boxesX*y].selected = true;
                    this.lastSelected.x = x;
                    this.lastSelected.y = y;
                    this.path = new Array();
                    this.path[0] = x + this.boxesX*y;
                }
                else {
                    if (this.lastSelected.x >= x-1 && this.lastSelected.x <= x+1) {
                        if (this.lastSelected.y >= y-1 && this.lastSelected.y <= y+1) {
                            if (this.lastSelected.x != x || this.lastSelected.y != y) {
                                this.boxes[Math.floor(x + this.boxesX*y)].selected = true;
                                this.lastSelected.x = x;
                                this.lastSelected.y = y;
                                this.path[this.path.length] = x + this.boxesX*y;
                            }
                        }
                    }
                }
            }
        }
    }
    drawBoxes();
}
function mouseup(event) {
    if (!selecting) 
        return;
    mousemove(event);
    selecting = false;
    this.lastSelected.x = -1;
    this.lastSelected.y = -1;
    
    var word = "";
    actualWord = "";
    for (var i = 0; i < this.path.length; i++) {
        var apa = this.path[i];
        
        var x = apa % this.boxesX;
        var y = Math.floor(apa / this.boxesX);
        word = word + x + "" + y;
        
        actualWord = actualWord + this.boxes[this.path[i]].letter;
    }
    
    var alreadySubmited = false;
    
    for (var i = 0; i < this.wordsSubmited.length; i++) {
        if (actualWord == this.wordsSubmited[i]) {
            alreadySubmited = true;
        }
    }
    if (!alreadySubmited) {
        this.submitWord(word);
        this.wordsSubmited[this.wordsSubmited.length] = actualWord;
    }
    
    for (var i = 0; i < this.boxes.length; i++) {
        this.boxes[i].selected = false;
    } 
    this.needToRepaint = true;
    drawBoxes();
    
}
function drawBoxes() {
    //context.fillStyle = "rgba(0, 0, 0, 0";
    //context.fillRect(0, 0, 500, 500);
    if (this.needToRepaint) {
        context.strokeStyle="#FFFFFF";
        context.fillStyle = '#F0F';
        context.font="72px lucida console";
        for(var i in this.boxes) {
            var box = this.boxes[i];

            if (box.selected) {
                context.strokeStyle = "rgb(255, 255, 255)";
                context.fillStyle = "rgba(175, 106, 0, .5)";
            }
            else {
                context.strokeStyle = "rgb(255, 255, 255)";
                context.fillStyle = "rgba(0, 0, 0, 1)";
            }
            roundRect(box.startX, box.startY, box.stopX-box.startX, box.stopY-box.startY, 10, true);

            context.fillStyle = '#FFF';
            context.fillText(box.letter, box.startX + this.charOffsetX, box.startY+this.charOffsetY);
        }
    }
    this.needToRepaint = false;
}
function roundRect(x, y, width, height, radius, fill, stroke) {
    if (typeof stroke == "undefined" ) {
        stroke = true;
    }
    if (typeof radius === "undefined") {
        radius = 5;
    }
    
    context.beginPath();
    context.moveTo(x + radius, y);
    context.lineTo(x + width - radius, y);
    context.quadraticCurveTo(x + width, y, x + width, y + radius);
    context.lineTo(x + width, y + height - radius);
    context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    context.lineTo(x + radius, y + height);
    context.quadraticCurveTo(x, y + height, x, y + height - radius);
    context.lineTo(x, y + radius);
    context.quadraticCurveTo(x, y, x + radius, y);
    context.closePath();
    
    if (stroke) {
        context.stroke();
    }
    if (fill) {
        context.fill();
    }        
}
function createBoxes() {
    for (var x = 0; x < this.boxesX; x++) {
        for (var y = 0; y < this.boxesY; y++) {
            this.boxes[x+this.boxesX*y] = {};
            this.boxes[x+this.boxesX*y].startX = x * (this.sizeX/this.boxesX);
            this.boxes[x+this.boxesX*y].stopX = (x+1) * (this.sizeX/this.boxesX);
            this.boxes[x+this.boxesX*y].startY = y * (this.sizeY/this.boxesY);
            this.boxes[x+this.boxesX*y].stopY = (y+1) * (this.sizeY/this.boxesY);
            this.boxes[x+this.boxesX*y].letter = this.letters.charAt(x+this.boxesX*y);
            this.boxes[x+this.boxesX*y].selected = false;
        }
    }
}

function submitWord(wordPoints) {
    var deferred = this.gameProxy.submitWord(this.gameId, wordPoints, this.player);
    deferred.done(function() {
        var apa = parent.gameProxy.getPoints(parent.gameId, parent.player);
        apa.done(function(data) {
            points = data;
            output();
        });
    });
}

function output() {
    document.getElementById("points").innerHTML = this.points;
}

var Timer;
var TotalSeconds;


function CreateTimer(TimerID, Time) {
    Timer = document.getElementById(TimerID);
    TotalSeconds = Time;
        
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function Tick() {
    if (TotalSeconds <= 0) {
        window.location = "result.xhtml";
        return;
    }
    
    TotalSeconds -= 1;
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}

function UpdateTimer() {
    var Seconds = TotalSeconds;

    var Minutes = Math.floor(Seconds / 60);
    Seconds -= Minutes * (60);

    var TimeStr = "" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)

    Timer.innerHTML = TimeStr;
}


function LeadingZero(Time) {
    return (Time < 10) ? "0" + Time : + Time;
}
